package com.sunday.electric.smack;


import com.sunday.electric.utils.SharePerferenceUtils;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;

public class SmackImpl implements Smack {

	private static final int PACKET_TIMEOUT = 30000;// 超时时间
	private static SmackImpl smackImp;
	private static XMPPTCPConnection mXMPPConnection;
	public static SmackImpl  getIns(){
		if(smackImp==null){
			XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
			builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
			builder.setDebuggerEnabled(true);
			XMPPTCPConnectionConfiguration config = builder.setServiceName(SmackConstants.SERVER_NAME)
					.setHost(SmackConstants.HOST).setPort(5222)
					.setUsernameAndPassword(SharePerferenceUtils.getIns().getUserId(),
							SharePerferenceUtils.getIns().getOAuth().getPassword())
					.build();
			mXMPPConnection = new XMPPTCPConnection(config);
			smackImp = new SmackImpl();
		}
		return smackImp;
	}

	/*public static SmackImpl  getIns(){
		if(smackImp==null){
			XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
			builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
			builder.setDebuggerEnabled(true);
			XMPPTCPConnectionConfiguration config = builder.setServiceName(SmackConstants.SERVER_NAME)
					.setHost(SmackConstants.HOST).setPort(5222)
					.setUsernameAndPassword(SharePerferenceUtils.getIns().getUserId(),
							SharePerferenceUtils.getIns().getOAuth().getPassword())
					.build();
			mXMPPConnection = new XMPPTCPConnection(config);
			smackImp = new SmackImpl();
		}
		return smackImp;
	}*/

	public XMPPTCPConnection getXMPPConnection() {
		return mXMPPConnection;
	}

	@Override
	public boolean login() {
		if(mXMPPConnection.isConnected()){
			mXMPPConnection.disconnect();
		}
		mXMPPConnection.setPacketReplyTimeout(PACKET_TIMEOUT);// 设置超时时间
		try{
			mXMPPConnection.connect();
			mXMPPConnection.login();
		}catch (Exception e){
			e.printStackTrace();
		}
		return mXMPPConnection.isAuthenticated();
	}

	public boolean isAuthenticated() {// 是否与服务器连接上，供本类和外部服务调用
		if (mXMPPConnection != null) {
			return (mXMPPConnection.isConnected() && mXMPPConnection
					.isAuthenticated());
		}
		return false;
	}

	public void loginOut(){
		if(mXMPPConnection!=null){
			mXMPPConnection.disconnect();
		}
	}



}
